<template>
  <div style="position:absolute;top:110px;bottom:-11%;left:0;right:0" v-loading="loading">
    <div class="cashier">
      <!-- 账户表单数据 -->
      <el-form :model="accountForm" ref="accountForm" :rules="rules" class="cashForm" v-loading="loadCash" :element-loading-text="loadingText">
        <div>
          <p>收银账号(需充值学员账号):</p>
          <el-form-item label prop="tel">
            <el-row type="flex" justify="space-between">
              <el-col :span="16">
                <el-input
                  v-model.trim="accountForm.tel"
                  @input="searchInfo"
                  :disabled="btnDisabled"
                ></el-input>
              </el-col>
              <el-col :span="6">
                <el-button
                  @click="sendvalid()"
                  :disabled="btnDisabled"
                  v-show="newStudent"
                >{{btnText}}</el-button>
                <el-button
                  @click="sendnotice()"
                  :disabled="btnDisabled2"
                  v-show="!newStudent"
                >{{noteText}}</el-button>
              </el-col>
            </el-row>
          </el-form-item>

          <div class="studentInfo">
            <div v-show="studentInfo" style="color:gray">
              <p>学员姓名:{{studentName}}</p>
              <p>学员手机号:{{studentPhone}}</p>
            </div>
          </div>
        </div>
        <div v-show="validCode">
          <P>验证码:</P>
          <el-form-item label prop="code">
            <el-input v-model.trim="accountForm.code"></el-input>
          </el-form-item>
        </div>
        <div>
          <p>收银金额:</p>
          <el-form-item label prop="amount">
            <el-input v-model.trim="accountForm.amount"></el-input>
          </el-form-item>

          <input
            type="password"
            v-model="QRcode"
            class="qrcode"
            @blur="qrcodeblur()"
            @focus="qrcodefocus()"
            @keydown="qrInput($event)"
          >
          <div class="cashBox">
            <el-button
              class="cashierClick"
              @click="comfireCashier"
              :loading="loadCash"
              :disabled="cashDisable"
            >收银</el-button>
          </div>
        </div>
      </el-form>

      <el-dialog title="余额购买" :visible.sync="dialogVisible" :append-to-body="true" :close-on-click-modal="false" :modal="false" @close="resetForm('purchaseForm')">
        <el-form :model="purchaseForm" label-width="140px" class="purchaseForm" ref="purchaseForm" :rules="rules2" v-loading="loadingPurchase">
          <el-form-item label="学员姓名:">
            <el-input v-model="purchaseForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="学员账号:">
            <el-input v-model="purchaseForm.account" disabled></el-input>
          </el-form-item>

          <!-- 产品卡 -->
          <div class="addBtnBox">
            <el-button @click="addProduct">增加产品</el-button>
          </div>
          <el-card class="box-card" v-for="(card,index) in packageData" :key="'packageData'+index">
            <template v-if="index!=0">
              <div slot="header" class="clearfix">
                <el-button
                  @click="removeProduct(index)"
                  id="closeIcon"
                  icon="el-icon-close"
                  type="text"
                ></el-button>
              </div>
            </template>
            <div class="text item" style="margin: 6px 0;padding: 10px 0 1px 0;">
              <el-form-item label="产品类型：">
                <el-select
                  v-model="purchaseForm.packageContains[index].payProductId"
                  @change="selectGet"
                >
                  <el-option
                    v-for="(pro,i) in packageData[0].productType"
                    :key="'pro'+i"
                    :label="pro.packageName"
                    :value="pro.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="产品名称：" v-show="purchaseForm.packageContains[index].otherType">
                <el-input
                  v-model.trim="purchaseForm.packageContains[index].remark"
                  class="divided_2"
                ></el-input>
              </el-form-item>
              <el-form-item label="数量：">
                <el-input v-model.trim="purchaseForm.packageContains[index].num" class="divided_2"></el-input>
              </el-form-item>
              <el-form-item label="金额：" v-show="purchaseForm.packageContains[index].otherType">
                <el-input
                  v-model.trim="purchaseForm.packageContains[index].payAmount"
                  class="divided_2"
                ></el-input>
              </el-form-item>
            </div>
          </el-card>

          <!-- 随单赠送 -->
          <el-card class="box-card" v-for="(card,index) in giftProduct" :key="'gift'+index">
            <div class="text item" style="margin: 6px 0;padding: 10px 0 1px 0;">
              <el-form-item label="产品类型：">
                <el-select v-model="purchaseForm.giftCard[index].payProductId" @change="selectGet">
                  <el-option
                    v-for="(pro,i) in card.productType"
                    :key="'pro'+i"
                    :label="pro.packageName"
                    :value="pro.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <span class="giftText">随单赠送</span>
              <el-form-item label="产品名称：" v-show="purchaseForm.giftCard[index].otherType">
                <el-input v-model.trim="purchaseForm.giftCard[index].remark" class="divided_2"></el-input>
              </el-form-item>
              <el-form-item label="数量：">
                <el-input v-model.trim="purchaseForm.giftCard[index].num" class="divided_2"></el-input>
              </el-form-item>
              <el-form-item label="金额：" v-show="purchaseForm.giftCard[index].otherType">
                <el-input v-model.trim="purchaseForm.giftCard[index].payAmount" class="divided_2"></el-input>
              </el-form-item>
            </div>
          </el-card>
          <el-form-item label="余额金额扣除：" style="margin-top:10px;" prop="amount">
            <el-input v-model.trim="purchaseForm.amount"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="dialog_close" @click="dialogVisible = false" :disabled="btnPurchse">取 消</el-button>
          <el-button
            class="dialog_confirm"
            type="primary"
            @click="submitPurchaseForm()"
            :disabled="btnPurchse"
          >确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 收银状态提示框 -->
    <div class="prompt" v-if="promptShow">
      <transition name="el-fade-in-linear">
        <div class="prompt-content">
          <div class="prompt_head back">
            <i class="el-icon-close" id="promptCloseIcon" @click="closeMyself"></i>
          </div>
          <div class="prompt_main">
            <div class="prompt_icon_wrap">
              <i class="el-icon-success" id="successIcon"></i>
              <div class="prompt_text">收款成功</div>
            </div>
            <p id="collection">¥{{actualPayment}}</p>
            <div class="prompt_paymentMethod">
              <span class="paymentMethod">支付方式:</span>
              <span class="paymentName">{{paymentMethod}}</span>
            </div>
          </div>
          <el-button
            class="dialog_confirm purchaseBtn"
            type="primary"
            @click="balancePurchase"
          >余额购买产品卡</el-button>
        </div>
      </transition>
    </div>
  </div>
</template>
<script>
import base from "../api/base.js";
import { ISO_8601 } from "moment";
export default {
  data() {
    var validateAmount1 = (rule, value, callback) => {
      var reg1 = /^[0-9]+([.]{1}[0-9]{1,2}){0,1}$/;
      var reg2 = /^[0-9]+([.]{1}[0-9]+){0,1}$/;
      if(reg2.test(value)){
         this.accountForm.amount=Number(this.accountForm.amount).toString()
        if(value>0){
          if(reg1.test((Number(value).toString()))){
            callback();
          }else{
            callback(new Error("最小收款单位不能低于分"));
          }
        }else{
          callback(new Error('输入金额需要大于零'))
        }
      }else{
        callback(new Error('输入格式有误'))
      }
    };
    var validateAmount2 = (rule, value, callback) => {
      var reg1 = /^[0-9]+([.]{1}[0-9]{1,2}){0,1}$/;
      var reg2 = /^[0-9]+([.]{1}[0-9]+){0,1}$/;
      if(reg2.test(value)){
         this.purchaseForm.amount=Number(this.purchaseForm.amount).toString()
        if(value>0){
          if(reg1.test((Number(value).toString()))){
            callback();
          }else{
            callback(new Error("最小收款单位不能低于分"));
          }
        }else{
          callback(new Error('输入金额需要大于零'))
        }
      }else{
        callback(new Error('输入格式有误'))
      }
    };
    
    return {
      QRcode: "",
      loadCash: false,
      cashDisable: false,
      loadingPurchase: false,
      btnPurchse: false,
      newStudent: true,
      switchCode: false,
      // 订单流水id
      accountId: "",
      // 账户表单数据
      accountForm: {
        memberId: "",
        tel: "",
        code: "",
        amount: ""
      },
      rules: {
        amount: [
          { required: true, message: "请填写收银金额", trigger: "blur" },
          { validator: validateAmount1, trigger: "blur" }
        ],
        tel: [{ required: true, message: "请填写账号", trigger: "blur" }]
        // code: [{ required: true, message: "请填写验证码", trigger: "blur" }],
      },
      // 余额购买表单数据
      purchaseForm: {
        username: "",
        account: "",
        memberId: "",
        // 产品卡
        packageContains: [
          {
            payProductId: "",
            num: "",
            remark: "",
            payAmount: "",
            tradeType: 2015,
            otherType: false
          }
        ],
        // 随单赠送卡
        giftCard: [
          {
            payProductId: "",
            num: "",
            remark: "",
            payAmount: "",
            tradeType: 2017,
            otherType: false
          }
        ],
        // 余额购买
        amount: ""
      },
      rules2: {
        amount: [
          { required: true, message: "请填写扣除金额", trigger: "blur" },
          { validator: validateAmount2, trigger: "blur" }
        ]
      },
      // 产品信息
      packageData: [{ productType: [] }],
      //   随单赠送产品信息
      giftProduct: [{ productType: [] }],

      btnText: "发送验证码",
      noteText: "发送短信通知",
      btnDisabled: false,
      btnDisabled2: true,
      validCode: false,
      studentInfo: false,
      studentName: "",
      studentPhone: "",
      dialogVisible: false,
      promptShow: false,
      loading: false,
      paymentMethod: "支付宝",
      t: "", // 等待支付时间的清除5min
      t2: "", // 条码需要密码的时间
      t3: "", // 轮询支付状态
      lastTime: null,
      nextTime: null,
      code: "",//条形码
      lastCode:'',//上一次的条形码
      studentAccount: "", //创建档案的学员账号
      actualPayment: "", //实际付款金额
      loadingText:'正在收银'
    };
  },
  methods: {
    //   发送验证码
    sendvalid() {
      this.$axios({
        url: base.baseUrl2 + "/v1/agent/sms/message-send",
        method: "POST",
        header: { "content-type": "application/x-www-form-urlencoded" },
        data: {
          // token: localStorage.token,
          type: "register",
          tel: this.accountForm.tel.trim()
        },
        transformRequest: [
          function(data) {
            let ret = "";
            for (let it in data) {
              ret +=
                encodeURIComponent(it) +
                "=" +
                encodeURIComponent(data[it]) +
                "&";
            }
            return ret;
          }
        ]
      })
        .then(res => {
          if (res.data.status == 4000) {
            this.alertTip(res.data.message);
          } else if (res.data.status == 2000) {
            this.btnDisabled = true;
            this.validCode = true;
            var totalTime = 60;
            var t = setInterval(() => {
              totalTime--;
              this.btnText = totalTime + "s";
              if (totalTime == 0) {
                clearInterval(t);
                this.btnText = "发送验证码";
                this.btnDisabled = false;
              }
            }, 1000);
          } else if (res.data.status == 2001) {
            this.$router.push("/login");
          }
        })
        .catch(error => {
          console.log(error);
          this.alertTip(
            "网络异常收银失败，请检查网络稍后再试"
          );
        });
    },
    // 发送短信通知
    sendnotice() {
      this.$axios({
        url: base.baseUrl2 + "/v1/agent/sms/message-send",
        method: "POST",
        header: { "content-type": "application/x-www-form-urlencoded" },
        data: {
          // token: localStorage.token,
          type: "recharge",
          tel: this.accountForm.tel.trim()
        },
        transformRequest: [
          function(data) {
            let ret = "";
            for (let it in data) {
              ret +=
                encodeURIComponent(it) +
                "=" +
                encodeURIComponent(data[it]) +
                "&";
            }
            return ret;
          }
        ]
      })
        .then(res => {
          if (res.data.status == 4000) {
            this.alertTip(res.data.message);
          } else if (res.data.status == 2000) {
            this.noteText = "已发送";
            this.btnDisabled2 = true;
          } else if (res.data.status == 2001) {
            this.$router.push("/login");
          }
        })
        .catch(error => {
          console.log(error);
          this.alertTip(
            "网络异常收银失败，请检查网络稍后再试"
          );
        });
    },
    // 搜索学员信息
    searchInfo() {
      var reg = /^1[3456789]\d{9}$/;
      this.loadCash = false;
      this.cashDisable = false;
      this.btnDisabled2 = false;
      this.noteText = "发送短信通知";
      this.studentAccount = "";
      if (!this.btnDisabled && reg.test(this.accountForm.tel.trim())) {
        this.validCode = false;
        this.$axios({
          url: base.baseUrl2 + "/v1/agent/agent-student/search-tel",
          method: "POST",
          header: { "content-type": "application/x-www-form-urlencoded" },
          data: {
            token: localStorage.token,
            // token: "9f063cd31dd559824941e3d47fc69abc#100230",
            tel: this.accountForm.tel.trim()
          },
          transformRequest: [
            function(data) {
              let ret = "";
              for (let it in data) {
                ret +=
                  encodeURIComponent(it) +
                  "=" +
                  encodeURIComponent(data[it]) +
                  "&";
              }
              return ret;
            }
          ]
        })
          .then(res => {
            this.btnDisabled = false;
            if (res.data.status == 4000) {
              this.alertTip(res.data.message);
            } else if (res.data.status == 2000) {
              if (res.data.data.member) {
                this.newStudent = false;
                this.studentName = res.data.data.member.fullName? res.data.data.member.fullName: res.data.data.member.nickname;
                this.studentPhone = res.data.data.member.mobile;
                this.accountForm.memberId = res.data.data.member.id;
                this.purchaseForm.memberId = res.data.data.member.id;
                this.purchaseForm.username = res.data.data.member.fullName? res.data.data.member.fullName: res.data.data.member.nickname;
                this.purchaseForm.account = res.data.data.member.userName;
                this.studentInfo = true;
                if (res.data.data.member.isAgentStudent == 0) {
                  this.alertTip(
                    "该学员不是本校的学员，建议重新更换手机号作为学员账户，否则收银成功后本校后台也无法查看该学员的学员档案"
                  );
                }
              } else {
                this.alertTip("没有该学员信息");
                this.studentInfo = false;
                this.newStudent = true;
                this.studentName = "";
                this.studentPhone = "";
                this.accountForm.memberId = "";
                this.purchaseForm.memberId = "";
                this.purchaseForm.username = "";
                this.purchaseForm.account = "";
              }
            } else if (res.data.status == 2001) {
              this.$router.push("/login");
            }
          })
          .catch(error => {
            this.btnDisabled = false;
            console.log(error);
            this.alertTip(
              "网络异常收银失败，请检查网络稍后再试"
            );
          });
      } else {
        this.studentName = "";
        this.studentPhone = "";
        this.studentInfo = false;
      }
    },
    // 收银事件
    comfireCashier() {
      var _this=this
      this.$refs.accountForm.validate(valid => {
        if (valid) {
          this.loadCash = true;
          this.loadingText='正在收银'
          this.cashDisable = true;
          var submitData = Object.assign({}, this.accountForm);
          this.$set(submitData, "token", localStorage.token);
          this.$axios({
            url: base.baseUrl2 + "/v1/account/face-pay/create-record",
            method: "POST",
            header: { "content-type": "application/x-www-form-urlencoded" },
            data: submitData,
            transformRequest: [
              function(data) {
                let ret = "";
                for (let it in data) {
                  ret +=
                    encodeURIComponent(it) +
                    "=" +
                    encodeURIComponent(data[it]) +
                    "&";
                }
                return ret;
              }
            ]
          })
            .then(res => {
              if (res.data.status == 4000) {
                this.alertTip(res.data.message);
                this.loadCash = false;
                this.cashDisable = false;
              } else if (res.data.status == 2000) {
                document.getElementsByClassName("qrcode")[0].focus();
                this.switchCode = true;
                this.accountId = res.data.data.memberAccountStatement.id;
                var _this = this;
                this.studentAccount = this.accountForm.tel;
                this.t = setTimeout(function() {
                  // if (_this.QRcode.length != 18) {
                    _this.alertTip("超时,请重新申请");
                    _this.loadCash = false;
                    _this.cashDisable = false;
                    _this.switchCode = false;
                    _this.accountForm.tel = "";
                    _this.accountForm.code = "";
                    _this.accountForm.amount = "";
                    _this.studentInfo = false;
                    _this.accountId=''
                  // } else {
                    clearTimeout(_this.t);
                  // }
                }, 300000);
              } else if (res.data.status == 2001) {
                this.loadCash = false;
                this.cashDisable = false;
                this.$router.push("/login");
              }
            })
            .catch(error => {
              this.loadCash = false;
              this.cashDisable = false;
              this.switchCode = false;
              this.accountForm.tel = "";
              this.accountForm.code = "";
              this.accountForm.amount = "";
              this.studentInfo = false;
              this.accountId=''
              console.log(error);
              this.alertTip(
                "网络异常收银失败，请检查网络稍后再试"
              );
            });
        } else {
          this.alertTip("选项有误,不能提交");
        }
      });
    },
    qrcodeblur() {
      if (this.switchCode) {
        document.getElementsByClassName("qrcode")[0].focus();
        console.log(this.switchCode);
      }
    },
    qrcodefocus() {
      console.log("focus");
    },
    // 键盘输入
    qrInput(e) {
      var _this=this
      let keycode = e.keyCode || e.which || e.charCode;
      this.nextTime = new Date();
      this.loadingText="正在收银"
      if (keycode === 13) {
        // console.log(this.code.length)
        if (this.lastTime && this.nextTime - this.lastTime < 50) {
          if (this.code.length >=16 && this.code.length <=30 && this.accountId!=''&&(this.lastCode==''||(this.lastCode!=''&&this.lastCode!=this.code))) {
            this.$axios({
              url: base.baseUrl2 + "/v1/account/face-pay/barcode-pay",
              method: "POST",
              header: { "content-type": "application/x-www-form-urlencoded" },
              data: {
                // token:'9f063cd31dd559824941e3d47fc69abc#100230',
                token: localStorage.token,
                memberAccountStatementId: this.accountId,
                authCode: this.code
              },
              transformRequest: [
                function(data) {
                  let ret = "";
                  for (let it in data) {
                    ret +=
                      encodeURIComponent(it) +
                      "=" +
                      encodeURIComponent(data[it]) +
                      "&";
                  }
                  return ret;
                }
              ]
            })
              .then(res => {
                this.lastCode=this.code
                if (res.data.status == 4000) {
                  document.getElementsByClassName("qrcode")[0].blur();
                  this.alertTip(res.data.message);
                  this.accountForm.tel = "";
                  this.accountForm.code = "";
                  this.accountForm.amount = "";
                  this.studentInfo = false;
                  clearTimeout(this.t);
                  clearInterval(this.t3);
                  clearTimeout(this.t2);
                  // console.log(this.t)
                  this.switchCode = false;
                  this.loadCash = false;
                  this.cashDisable = false;
                  this.code = "";
                  this.lastCode=''
                  this.accountId=''
                } else if (res.data.status == 2000) {
                  document.getElementsByClassName("qrcode")[0].blur();
                  this.paymentMethod =
                    res.data.data.memberAccountStatement.tradeSourceContent;
                  this.actualPayment =
                    res.data.data.memberAccountStatement.receiptAmount;
                  this.promptShow = true;
                  this.accountId = "";
                  this.accountForm.tel = "";
                  this.accountForm.code = "";
                  this.accountForm.amount = "";
                  this.studentInfo = false;
                  clearTimeout(this.t);
                  clearInterval(this.t3);
                  clearTimeout(this.t2);
                  // console.log(this.t)
                  this.switchCode = false;
                  this.loadCash = false;
                  this.cashDisable = false;
                  this.code = "";
                  this.lastCode=''
                } else if (res.data.status == 1003) {
                  this.loadingText="正在收银("+res.data.message+")"
                  this.code=''
                  clearTimeout(this.t);
                  clearInterval(this.t3);
                  clearTimeout(this.t2);
                  this.t2 = setTimeout(function() {
                    _this.alertTip("付款已超时，请重新刷新二维码付款");
                    document.getElementsByClassName("qrcode")[0].blur();
                    _this.loadCash = false;
                    _this.cashDisable = false;
                    _this.switchCode = false;
                    _this.accountForm.tel = "";
                    _this.accountForm.code = "";
                    _this.accountForm.amount = "";
                    _this.studentInfo = false;
                    _this.accountId='';
                    _this.code="";
                    _this.lastCode="";
                    clearTimeout(_this.t2);
                    clearInterval(_this.t3);
                }, 60000);
                  this.t3=setInterval(function(){
                    _this.$axios({
                        url: base.baseUrl2 + "/v1/account/face-pay/query-order",
                        method: "POST",
                        header: { "content-type": "application/x-www-form-urlencoded" },
                        data: {
                          // token:'9f063cd31dd559824941e3d47fc69abc#100230',
                          token: localStorage.token,
                          memberAccountStatementId: _this.accountId,
                          // authCode: _this.code
                        },
                        transformRequest: [
                          function(data) {
                            let ret = "";
                            for (let it in data) {
                              ret +=
                                encodeURIComponent(it) +
                                "=" +
                                encodeURIComponent(data[it]) +
                                "&";
                            }
                            return ret;
                          }
                        ]
                      }).then(res=>{
                        if (res.data.status == 4000){
                          document.getElementsByClassName("qrcode")[0].blur();
                            _this.alertTip(res.data.message);
                            _this.accountForm.tel = "";
                            _this.accountForm.code = "";
                            _this.accountForm.amount = "";
                            _this.studentInfo = false;
                            clearInterval(_this.t3);
                            clearTimeout(_this.t2);
                            _this.switchCode = false;
                            _this.loadCash = false;
                            _this.cashDisable = false;
                            _this.code = "";
                            _this.lastCode=""
                            _this.accountId=''
                        }else if(res.data.status == 2000){
                          if(res.data.data.memberAccountStatement.isValid==1){
                              document.getElementsByClassName("qrcode")[0].blur();
                              _this.paymentMethod =res.data.data.memberAccountStatement.tradeSourceContent;
                              _this.actualPayment =res.data.data.memberAccountStatement.receiptAmount;
                              _this.promptShow = true;
                              _this.accountId = "";
                              _this.accountForm.tel = "";
                              _this.accountForm.code = "";
                              _this.accountForm.amount = "";
                              _this.studentInfo = false;
                              clearInterval(_this.t3);
                              clearTimeout(_this.t2);
                              // console.log(this.t)
                              _this.switchCode = false;
                              _this.loadCash = false;
                              _this.cashDisable = false;
                              _this.code = "";
                              _this.lastCode=''
                          }    
                        }else if(res.data.status == 2001){
                            document.getElementsByClassName("qrcode")[0].blur();
                            _this.accountForm.tel = "";
                            _this.accountForm.code = "";
                            _this.accountForm.amount = "";
                            _this.studentInfo = false;
                            clearInterval(_this.t3);
                            clearTimeout(_this.t2);
                            // console.log(this.t)
                            _this.switchCode = false;
                            _this.loadCash = false;
                            _this.cashDisable = false;
                            _this.code = "";
                            _this.lastCode=''
                            _this.accountId=''
                            _this.$router.push("/login");
                        }
                    })
                  },3000)  
                } else if (res.data.status == 2001) {
                  document.getElementsByClassName("qrcode")[0].blur();
                  this.accountForm.tel = "";
                  this.accountForm.code = "";
                  this.accountForm.amount = "";
                  this.studentInfo = false;
                  clearTimeout(this.t);
                  clearInterval(this.t3);
                  clearTimeout(this.t2);
                  // console.log(this.t)
                  this.switchCode = false;
                  this.loadCash = false;
                  this.cashDisable = false;
                  this.code = "";
                  this.lastCode=''
                  this.accountId=''
                  this.$router.push("/login");
                }
              })
              .catch(error => {
                document.getElementsByClassName("qrcode")[0].blur();
                clearTimeout(this.t);
                clearInterval(this.t3);
                clearTimeout(this.t2);
                this.accountForm.tel = "";
                this.accountForm.code = "";
                this.accountForm.amount = "";
                this.studentInfo = false;
                this.switchCode = false;
                this.loadCash = false;
                this.cashDisable = false;
                this.code = "";
                this.lastCode="";
                this.accountId=""
                console.log(error);
                this.alertTip(
                  "网络异常收银失败，请检查网络稍后再试"
                );
              })
              .finally(() => {
                clearTimeout(this.t);
                // this.accountForm.tel = "";
                // this.accountForm.code = "";
                // this.accountForm.amount = "";
                // this.studentInfo = false;
                // this.switchCode = false;
                // this.loadCash = false;
                // this.cashDisable = false;
                // this.code = "";
              });
          } else if(this.accountId==''){
            this.alertTip("订单已失效,请重新申请");
            clearTimeout(this.t);
            clearInterval(this.t3);
            clearTimeout(this.t2);
            this.switchCode = false;
            this.loadCash = false;
            this.cashDisable = false;
            this.accountForm.tel = "";
            this.accountForm.code = "";
            this.accountForm.amount = "";
            this.studentInfo = false;
            this.code = "";
            // this.lastCode=""
            // this.accountId=''
          }else{
            this.alertTip("付款码格式有误");
            console.log(this.code)
            clearTimeout(this.t);
            clearInterval(this.t3);
            clearTimeout(this.t2);
            this.switchCode = false;
            this.loadCash = false;
            this.cashDisable = false;
            this.accountForm.tel = "";
            this.accountForm.code = "";
            this.accountForm.amount = "";
            this.studentInfo = false;
            this.code = "";
          }
        }
        this.code = "";
        this.lastTime = null;
        e.preventDefault();
      } else {
        if (!this.lastTime) {
          this.code = String.fromCharCode(keycode);
          console.log(this.code)
        } else {
          if (this.nextTime - this.lastTime < 50) {
            console.log(this.nextTime - this.lastTime)
            this.code += String.fromCharCode(keycode);
            console.log(this.code)
          } else {
            console.log(this.nextTime - this.lastTime)
            this.code=String.fromCharCode(keycode)
          }
        }
        this.lastTime = this.nextTime;
      }
    },
    // 点击余额购买事件
    balancePurchase() {
      this.getAgentPackageList()
      var reg = /^1[3456789]\d{9}$/;
      if (reg.test(this.studentAccount.trim())) {
        this.$axios({
          url: base.baseUrl2 + "/v1/agent/agent-student/search-tel",
          method: "POST",
          header: { "content-type": "application/x-www-form-urlencoded" },
          data: {
            token: localStorage.token,
            // token: "9f063cd31dd559824941e3d47fc69abc#100230",
            tel: this.studentAccount.trim()
          },
          transformRequest: [
            function(data) {
              let ret = "";
              for (let it in data) {
                ret +=
                  encodeURIComponent(it) +
                  "=" +
                  encodeURIComponent(data[it]) +
                  "&";
              }
              return ret;
            }
          ]
        })
          .then(res => {
            if (res.data.status == 4000) {
              this.alertTip(res.data.message);
            } else if (res.data.status == 2000) {
              if (res.data.data.member) {
                this.purchaseForm.memberId = res.data.data.member.id;
                this.purchaseForm.username = res.data.data.member.fullName? res.data.data.member.fullName: res.data.data.member.nickname;
                this.purchaseForm.account = res.data.data.member.userName;
                this.dialogVisible = true;
              } else {
                this.alertTip("没有该学员信息");
                this.purchaseForm.memberId = "";
                this.purchaseForm.username = "";
                this.purchaseForm.account = "";
              }
            } else if (res.data.status == 2001) {
              this.$router.push("/login");
            }
          })
          .catch(error => {
            console.log(error);
            this.alertTip(
              "网络异常收银失败，请检查网络稍后再试"
            );
          });
      } else {
        this.alertTip("手机号码格式有误");
      }
    },
    // 关闭提示框
    closeMyself() {
      this.promptShow = false;
      this.studentAccount = "";
    },
    // 获取代理商设置的套餐列表
    getAgentPackageList() {
      this.$axios({
        url: base.baseUrl2 + "/v1/agent/agent-package/list",
        method: "POST",
        header: { "content-type": "application/x-www-form-urlencoded" },
        data: {
          token: localStorage.token,
          // token: "9f063cd31dd559824941e3d47fc69abc#100230",
          type: 1
        },
        transformRequest: [
          function(data) {
            let ret = "";
            for (let it in data) {
              ret +=
                encodeURIComponent(it) +
                "=" +
                encodeURIComponent(data[it]) +
                "&";
            }
            return ret;
          }
        ]
      })
        .then(res => {
          if (res.data.status == 4000) {
            this.alertTip(res.data.message);
          } else if (res.data.status == 2000) {
            this.packageData[0].productType = res.data.data.productPackage;
            this.packageData[0].productType.push(res.data.data.otherPackage[0]);
            this.giftProduct[0].productType = this.packageData[0].productType;
          } else if (res.data.status == 2001) {
            this.$router.push("/login");
          }
        })
        .catch(error => {
          console.log(error);
          this.alertTip(
            "网络异常收银失败，请检查网络稍后再试"
          );
        });
    },
    // 添加产品卡
    addProduct() {
      this.packageData.push(this.packageData[0]);
      this.purchaseForm.packageContains.push({
        payProductId: "",
        num: "",
        remark: "",
        payAmount: "",
        tradeType: 2015,
        otherType: false
      });
    },
    // 删除产品卡
    removeProduct(index) {
      this.$confirm("是否确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.packageData.splice(index, 1);
          this.purchaseForm.packageContains.splice(index, 1);
        })
        .catch(error => {
          console.log(error);
          this.alertTip(
            "网络异常收银失败，请检查网络稍后再试"
          );
        });
    },
    // 产品卡的选择
    selectGet() {
      // 产品套餐卡
      this.purchaseForm.packageContains.forEach(el => {
        if (el.payProductId == 99) {
          el.otherType = true;
        } else {
          el.otherType = false;
        }
      });
      // 随单赠送
      this.purchaseForm.giftCard.forEach(el => {
        if (el.payProductId == 99) {
          el.otherType = true;
        } else {
          el.otherType = false;
        }
        if(el.payProductId==''){
            el.num='';
            el.remark='';
            el.payAmount=''
        }
      });
    },
    // 余额购买提交事件
    submitPurchaseForm() {
      this.$refs.purchaseForm.validate(valid => {
        if (valid) {  
          this.purchaseForm.packageContains.some(el => {
            if (el.num == "") {
              this.alertTip("产品卡数量不能为空");
              return true;
            }
            if(/^[0-9.]+$/.test(el.num)){
                el.num=Number(el.num).toString()
                if(el.num<=0){
                    this.alertTip('产品卡数量需要大于零');
                    return true;
                }
                if(!(/^[1-9]\d*$/.test(el.num))){
                    this.alertTip('产品卡数量输入格式有误');
                    return true;
                }
            }else{
                this.alertTip("产品卡数量输入格式有误");
                return true;
            }
            if (el.payProductId == "") {
              this.alertTip("产品卡类型不能为空");
              return true;
            }
            if(el.payProductId == 99){
                if(el.num==''){
                    this.alertTip("产品卡数量不能为空");
                    return true;
                };
                if(el.remark==''){
                    this.alertTip("产品名称不能为空");
                    return true;
                };
                if(el.payAmount==''){
                    this.alertTip("产品卡金额不能为空");
                    return true;
                };
                if(/^[0-9]+([.]{1}[0-9]+){0,1}$/.test(el.payAmount)){
                    el.payAmount=Number(el.payAmount).toString()
                    if(el.payAmount>0){
                        if(/^[0-9]+([.]{1}[0-9]{1,2}){0,1}$/.test(el.payAmount)){
                        }else{
                            this.alertTip('产品金额最小收款单位不能低于分')
                            return true
                        }
                    }else{
                        this.alertTip('输入金额需要大于零')
                        return true;
                    }
                }else{
                    this.alertTip('输入的金额格式有误')
                    return true;
                }
            }
            if((this.purchaseForm.giftCard[0].payProductId == ""&&this.purchaseForm.giftCard[0].num==''&&this.purchaseForm.giftCard[0].remark==''&&this.purchaseForm.giftCard[0].payAmount=='')||(this.purchaseForm.giftCard[0].payProductId != ""&&this.purchaseForm.giftCard[0].num!='')){
              if(this.purchaseForm.giftCard[0].payProductId != ""){
                    if(/^[0-9.]+$/.test(this.purchaseForm.giftCard[0].num)){
                        this.purchaseForm.giftCard[0].num=Number(this.purchaseForm.giftCard[0].num).toString()
                        if(this.purchaseForm.giftCard[0].num<=0){
                            this.alertTip('随单赠送的产品卡数量需要大于零');
                            return true;
                        }
                        if(!(/^[1-9]\d*$/.test(this.purchaseForm.giftCard[0].num))){
                            this.alertTip('随单赠送的产品卡数量输入格式有误');
                            return true;
                        }
                    }else{
                        this.alertTip("随单赠送的产品卡数量输入格式有误");
                        return true;
                    }
                }
                if(this.purchaseForm.giftCard[0].payProductId ==99){
                    if(/^[0-9.]+$/.test(this.purchaseForm.giftCard[0].num)){
                        this.purchaseForm.giftCard[0].num=Number(this.purchaseForm.giftCard[0].num).toString()
                        if(this.purchaseForm.giftCard[0].num<=0){
                            this.alertTip('随单赠送的产品卡数量需要大于零');
                            return true;
                        }
                        if(!(/^[1-9]\d*$/.test(this.purchaseForm.giftCard[0].num))){
                            this.alertTip('随单赠送的产品卡数量输入格式有误');
                            return true;
                        }
                    }else{
                        this.alertTip("随单赠送的产品卡数量输入格式有误");
                        return true;
                    }
                    if(/^[0-9]+([.]{1}[0-9]+){0,1}$/.test(this.purchaseForm.giftCard[0].payAmount)){
                        this.purchaseForm.giftCard[0].payAmount=Number(this.purchaseForm.giftCard[0].payAmount).toString()
                        if(this.purchaseForm.giftCard[0].payAmount>0){
                            if(/^[0-9]+([.]{1}[0-9]{1,2}){0,1}$/.test(this.purchaseForm.giftCard[0].payAmount)){
                            }else{
                                this.alertTip('产品金额最小收款单位不能低于分')
                                return true
                            }
                        }else{
                            this.alertTip('输入金额需要大于零')
                            return true;
                        }
                    }else{
                        this.alertTip('输入的金额格式有误')
                        return true;
                    }
            }
            }else{
                if(this.purchaseForm.giftCard[0].payProductId != ""){
                    if(this.purchaseForm.giftCard[0].num==''){
                        this.alertTip("随单赠送的产品卡数量不能为空")
                        return true
                    }
                }
                if(this.purchaseForm.giftCard[0].num != ""){
                    if(this.purchaseForm.giftCard[0].payProductId==''){
                        this.alertTip("随单赠送的产品类型不能为空")
                        return true
                    }
                }
            }
            if(this.purchaseForm.giftCard[0].payProductId ==99){
                if(this.purchaseForm.giftCard[0].num==''){
                    this.alertTip('随单赠送中的产品卡数量不能为空')
                    return true;
                }
                if(this.purchaseForm.giftCard[0].remark==''){
                    this.alertTip('随单赠送中的产品名称不能为空')
                    return true;
                }
                if(this.purchaseForm.giftCard[0].payAmount==''){
                    this.alertTip('随单赠送中的产品卡金额不能为空')
                    return true;
                }
            }
            this.$confirm("确定提交?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消"
            }).then(() => {
              var submitData = {};
              this.btnPurchse = true;
              this.loadingPurchase = true;
              submitData.amount = this.purchaseForm.amount;
              submitData.memberId = this.purchaseForm.memberId;
              submitData.packageContains = [];
              this.purchaseForm.packageContains.forEach((el, index) => {
                submitData.packageContains.push({});
                submitData.packageContains[index].num = el.num;
                submitData.packageContains[index].payAmount = el.payAmount;
                submitData.packageContains[index].payProductId =
                  el.payProductId;
                submitData.packageContains[index].remark = el.remark;
                submitData.packageContains[index].tradeType = el.tradeType;
              });
              if(this.purchaseForm.giftCard[0].payProductId!=''){
                submitData.packageContains.push({});
              submitData.packageContains[
                submitData.packageContains.length - 1
              ].num = this.purchaseForm.giftCard[0].num;
              submitData.packageContains[
                submitData.packageContains.length - 1
              ].payAmount = this.purchaseForm.giftCard[0].payAmount;
              submitData.packageContains[
                submitData.packageContains.length - 1
              ].payProductId = this.purchaseForm.giftCard[0].payProductId;
              submitData.packageContains[
                submitData.packageContains.length - 1
              ].remark = this.purchaseForm.giftCard[0].remark;
              submitData.packageContains[
                submitData.packageContains.length - 1
              ].tradeType = this.purchaseForm.giftCard[0].tradeType;
              }
              submitData.token = localStorage.token;
              submitData.packageContains = JSON.stringify(
                submitData.packageContains
              );
              this.$axios({
                url: base.baseUrl2 + "/v1/account/member-account/consume",
                method: "POST",
                header: { "content-type": "application/x-www-form-urlencoded" },
                data: submitData,
                transformRequest: [
                  function(data) {
                    let ret = "";
                    for (let it in data) {
                      ret +=
                        encodeURIComponent(it) +
                        "=" +
                        encodeURIComponent(data[it]) +
                        "&";
                    }
                    return ret;
                  }
                ]
              })
                .then(res => {
                  this.loadingPurchase = false;
                  this.btnPurchse = false;
                  if (res.data.status == 4000) {
                    this.alertTip(res.data.message);
                  } else if (res.data.status == 2000) {
                    this.$alert(res.data.data, "提示", {
                      confirmButtonText: "确定",
                      callback: action => {
                        this.dialogVisible = false;
                      }
                    });
                  } else if (res.data.status == 2001) {
                    this.$router.push("/login");
                  }
                })
                .catch(error => {
                  this.loadingPurchase = false;
                  this.btnPurchse = false;
                  console.log(error);
                  this.alertTip(
                    "网络异常收银失败，请检查网络稍后再试"
                  );
                });
            });
          });
        } else {
          this.alertTip("选项有误,不能提交");
        }
      });
    },
    // 重置表单数据
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.packageData.splice(1);
      this.purchaseForm.packageContains.splice(0);
      this.purchaseForm.packageContains.push({
        payProductId: "",
        num: "",
        remark: "",
        payAmount: "",
        tradeType: 2015,
        otherType: false
      });
      this.purchaseForm.giftCard = [];
      this.purchaseForm.giftCard.push({
        payProductId: "",
        num: "",
        remark: "",
        payAmount: "",
        tradeType: 2017,
        otherType: false
      });
    },
    alertTip(msg) {
      this.$alert(msg, "提示", {
        confirmButtonText: "确定"
      });
    }
  },
  created() {
    // this.getAgentPackageList();
  },
};
</script>
<style scoped>
.qrcode {
  width: 0px;
  height: 0px;
  outline: 0;
  border: 0;
  opacity: 0;
}
.qrcode ::-moz-focus-inner {
  outline: none;
  border: none;
}
.cashier {
  /* width: 500px; */
  width: 80%;
  max-width: 700px;
  padding: 40px 120px 30px 60px;
  border: 1px solid black;
  margin: 20px auto auto 20px;
  height: 100%;
  max-height: 500px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  box-sizing: border-box;
}
.cashForm {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  box-sizing: border-box;
}
.cashBox {
  display: flex;
  justify-content: flex-end;
}
/*收银成功页面 begin*/
.prompt {
  width: 480px;
  height: 420px;
  position: absolute;
  color: black;
  font-size: 16px;
  border: 1px solid black;
  top: 50%;
  left: 50%;
  margin-top: -210px;
  margin-left: -240px;
  background: white;
}
.prompt_icon_wrap {
  text-align: center;
}
#successIcon {
  color: #ff0000;
  font-size: 84px;
  margin: 80px auto 20px;
}
.prompt_text {
  font-size: 16px;
  height: 22px;
}
.prompt_paymentMethod {
  margin: 10px 20px;
  padding: 16px 10px;
  border: 1px solid black;
  position: relative;
}
#promptCloseIcon {
  position: absolute;
  right: 10px;
  top: 10px;
  font-size: 22px;
  font-weight: bold;
  cursor: pointer;
}
#collection {
  height: 22px;
  margin: 30px auto 10px 20px;
}
.paymentMethod {
  display: inline-block;
  height: 20px;
  line-height: 20px;
  color: #606366;
  font-size: 14px;
}
.paymentName {
  display: inline-block;
  height: 20px;
  line-height: 20px;
  color: #606366;
  font-size: 14px;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -21px;
  margin-top: -10px;
}
.purchaseBtn {
  float: right;
  margin-right: 40px;
  margin-top: 26px;
}
/*收银成功页面 end*/

/*余额购买弹窗begin*/
.giftText {
  float: right;
  margin-top: -30px;
  margin-right: 50px;
  color: #aaa;
}
.addBtnBox {
  text-align: right;
}
.box-card {
  margin-top: 10px;
}
#closeIcon {
  position: relative;
  left: 96%;
  font-size: 22px;
}
/*余额购买弹窗end*/
</style>

